﻿using Chloe.SqlServer;
using SorketServer.Common;
using SorketServer.HYModel;
using SorketServer.TBModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static SorketServer.LedDll;

namespace SorketServer
{
    public partial class Form1 : Form
    {
        bool needClose = false;
        int hProgram;//节目句柄
        int nResult;
        WATERBORDERINFO info;
        LedDll.FONTPROP fontProp10;
        LedDll.FONTPROP fontProp12;
        LedDll.FONTPROP fontProp14;

        LedDll.PLAYPROP playProp;
        public Form1()
        {
            InitializeComponent();
            this.Load += Form1_Load;
            this.FormClosing += Form1_FormClosing;

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            needClose = true;
        }
        List<DepartCountDto> list;
        //private void Form1_Load(object sender, EventArgs e)
        //{
        //    Task.Factory.StartNew(() =>
        //    {
        //        IPAddress ip = IPAddress.Parse("127.0.0.1");
        //        IPEndPoint ipe = new IPEndPoint(ip, 8089);//把ip和端口转化为IPEndPoint实例

        //        Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
        //        server.Bind(ipe);//绑定2000端口
        //        server.Listen(0);//开始监听
        //        Socket temp = null;
        //        while (!needClose)
        //        {
        //            temp = server.Accept();//为新建连接创建新的Socket。
        //            string recvStr = "";
        //            byte[] recvBytes = new byte[10240];
        //            int bytes;
        //            bytes = temp.Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息
        //            recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes);
        //            string[] strarray = recvStr.Split(';');

        //            string accessPath = ConfigurationManager.AppSettings["path"].ToString();
        //            AccessDbClass accessdb = new AccessDbClass(accessPath);
        //            string sendStr = "";
        //            if (strarray[0] == "1")
        //            {
        //                DataTable result1 = accessdb.SelectToDataTable(strarray[1]);
        //                if (result1.Rows.Count > 0)
        //                {
        //                    sendStr = result1.Rows[0][0].ToString();
        //                }
        //            }
        //            else
        //            {
        //                accessdb.ExecuteSQLNonquery(strarray[1]);
        //            }

        //            //string sql2 = string.Format("SELECT USERID FROM USERINFO WHERE Badgenumber = '{0}'", "2");
        //            accessdb.Close();

        //            byte[] bs = Encoding.UTF8.GetBytes(sendStr);
        //            temp.Send(bs, bs.Length, 0);//返回客户端成功信息
        //            temp.Close();
        //            GC.Collect();
        //        }
        //    });
        //}


        void setBaseInfo()
        {
            int nResult;
            LedDll.COMMUNICATIONINFO CommunicationInfo = new LedDll.COMMUNICATIONINFO();//定义一通讯参数结构体变量用于对设定的LED通讯，具体对此结构体元素赋值说明见COMMUNICATIONINFO结构体定义部份注示
            CommunicationInfo.SendType = 0;//设为固定IP通讯模式，即TCP通讯
            CommunicationInfo.IpStr = ConfigurationManager.AppSettings["IP"].ToString();//给IpStr赋值LED控制卡的IP
            CommunicationInfo.LedNumber = 1;//LED屏号为1，注意socket通讯和232通讯不识别屏号，默认赋1就行了，485必需根据屏的实际屏号进行赋值
            nResult = LedDll.LV_SetBasicInfo(ref CommunicationInfo, 2, 288, 176);//设置屏参，屏的颜色为2即为双基色，64为屏宽点数，32为屏高点数，具体函数参数说明见函数声明注示
            if (nResult != 0)//如果失败则可以调用LV_GetError获取中文错误信息
            {
                string ErrStr;
                ErrStr = LedDll.LS_GetError(nResult);
              //  MessageBox.Show(ErrStr);
            }
            else
            {
               // MessageBox.Show("设置成功");
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            setBaseInfo();
            //if (ConfigurationManager.AppSettings["Led"].ToString() != "0")
            //{
            //    LEDJob ledJob = new LEDJob();
            //    ledJob.DrawFirst();
            //    ledJob.DrawSecond();
            //    ledJob.DrawDepart();
            //    ledJob.Save();
            //}


            MyJob myjob = new MyJob();
            myjob.Start();
            Task.Factory.StartNew(() =>
            {
                IPAddress ip = IPAddress.Parse("127.0.0.1");
                IPEndPoint ipe = new IPEndPoint(ip, 8089);//把ip和端口转化为IPEndPoint实例

                Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
                server.Bind(ipe);//绑定2000端口
                server.Listen(0);//开始监听
                Socket temp = null;
                while (!needClose)
                {
                    temp = server.Accept();//为新建连接创建新的Socket。
                    string recvStr = "";
                    byte[] recvBytes = new byte[10240];
                    int bytes;
                    bytes = temp.Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息
                    recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes);
                    if (recvStr == "OK")
                    {
                        MyJob myjob1 = new MyJob();
                        myjob1.Start();
                        setBaseInfo();
                        if (ConfigurationManager.AppSettings["Led"].ToString() != "0")
                        {
                            LEDJob ledJob1 = new LEDJob();
                            ledJob1.DrawFirst();
                            ledJob1.DrawSecond();
                            ledJob1.DrawDepart();
                            ledJob1.Save();
                        }
                    }
                    string sendStr = "";
                    byte[] bs = Encoding.UTF8.GetBytes(sendStr);
                    temp.Send(bs, bs.Length, 0);//返回客户端成功信息
                    temp.Close();
                    GC.Collect();
                }
            });
            int oldCount = -1;
            Task.Run(() =>
            {
                while (!needClose)
                {
                    if (DateTime.Now.Hour == 1)
                    {
                        MyJob myjob2 = new MyJob();
                        myjob2.Start();
                    }
                    var   list = CarHelper.GetDepartCount().Sum(c=>c.DepartCount);
                    if (oldCount == -1 || oldCount != list)
                    { 
                        oldCount = list;
                        LEDJob ledJob1 = new LEDJob();
                        ledJob1.DrawFirst();
                        ledJob1.DrawSecond();
                        ledJob1.DrawDepart();
                        ledJob1.Save();
                        Thread.Sleep(30 * 1000);
                    }
                   
                }

            });

            //InitData();
            //list = CarHelper.GetDepartCount();

            //LedDll.COMMUNICATIONINFO CommunicationInfo = new LedDll.COMMUNICATIONINFO();//定义一通讯参数结构体变量用于对设定的LED通讯，具体对此结构体元素赋值说明见COMMUNICATIONINFO结构体定义部份注示
            //CommunicationInfo.SendType = 0;//设为固定IP通讯模式，即TCP通讯
            //CommunicationInfo.IpStr = ConfigurationManager.AppSettings["IP"].ToString(); ;//给IpStr赋值LED控制卡的IP
            //CommunicationInfo.LedNumber = 1;//LED屏号为1，注意socket通讯和232通讯不识别屏号，默认赋1就行了，485必需根据屏的实际屏号进行赋值
            //hProgram = LedDll.LV_CreateProgram(288, 176, 2);
            //CreateFirst();
            //CreateSecond();
            //int page = (int)Math.Ceiling(((decimal)list.Count) / 10);
            //for (var i = 1; i <= page; i++)
            //{
            //    nResult = LedDll.LV_AddProgram(hProgram, i + 2, 10, 1);
            //    CreateCarPlate(i + 2, list.Skip((i - 1) * 8).Take(8).ToList());
            //}


            //nResult = LedDll.LV_Send(ref CommunicationInfo, hProgram);//发送，见函数声明注示
            //LedDll.LV_DeleteProgram(hProgram);
            //if (nResult != 0)//如果失败则可以调用LV_GetError获取中文错误信息
            //{
            //    string ErrStr;
            //    ErrStr = LedDll.LS_GetError(nResult);

            //}
            //else
            //{

            //}

        }

        void CreateCarPlate(int no, List<DepartCountDto> dtos)
        {
            int area = 1;
            LedDll.AREARECT areaReact = GetReact(0, 4, 288, 16);
            LedDll.LV_AddImageTextArea(hProgram, no, area, ref areaReact, 0);
            nResult = LedDll.LV_AddMultiLineTextToImageTextArea(hProgram, no, area, LedDll.ADDTYPE_STRING, "江苏太白集团有限公司", ref fontProp12, ref playProp, 2, 0);//通过字符串添加一个多行文本到图文区，参数说明见声明注示
            string str1 = "部门\r\n";
            string str2 = "人数\r\n";
            for (var i = 0; i < dtos.Count; i++)
            {
                str1 = str1 + dtos[i].DepartName + "\r\n";
                str2 = str2 + dtos[i].DepartCount + "人" + "\r\n";
            }
            areaReact = GetReact(0, 30, 140, 140);
            area++;
            LedDll.LV_AddImageTextArea(hProgram, no, area, ref areaReact, 0);

            nResult = LedDll.LV_AddMultiLineTextToImageTextArea(hProgram, no, area, LedDll.ADDTYPE_STRING, str1, ref fontProp10, ref playProp, 2, 0);//通过字符串添加一个多行文本到图文区，参数说明见声明注示

            areaReact = GetReact(145, 30, 140, 140);
            area++;
            LedDll.LV_AddImageTextArea(hProgram, no, area, ref areaReact, 0);

            nResult = LedDll.LV_AddMultiLineTextToImageTextArea(hProgram, no, area, LedDll.ADDTYPE_STRING, str2, ref fontProp10, ref playProp, 2, 0);//通过字符串添加一个多行文本到图文区，参数说明见声明注示

        }


        void CreateFirst()
        {
            LedDll.LV_AddProgram(hProgram, 1, 10, 1);
            LedDll.AREARECT areaReact = GetReact(10, 4, 270, 170);
            nResult = LedDll.LV_AddImageTextArea(hProgram, 1, 1, ref areaReact, 0);
            nResult = LedDll.LV_AddFileToImageTextArea(hProgram, 1, 1, "101.jpg", ref playProp);
            // nResult = LedDll.LV_AddFileToImageTextArea(hProgram, 1, 1, "102.jpg", ref playProp);

        }
        void CreateSecond()
        {
            LedDll.LV_AddProgram(hProgram, 2, 10, 1);
            LedDll.AREARECT areaReact = GetReact(10, 4, 270, 170);
            nResult = LedDll.LV_AddImageTextArea(hProgram, 2, 1, ref areaReact, 0);
            // nResult = LedDll.LV_AddFileToImageTextArea(hProgram, 1, 1, "101.jpg", ref playProp);
            nResult = LedDll.LV_AddFileToImageTextArea(hProgram, 2, 1, "102.jpg", ref playProp);

        }
        string GetNewStr(string str, int total, bool left)
        {
            int len = GetLength(str);
            string temp = " ";
            int templen = (total - len) / 2;
            for (int i = 0; i < templen; i++)
            {
                str = temp + str;
                str = str + temp;
            }
            return str;
        }
        int GetLength(string str)
        {
            if (str.Length == 0) return 0;
            ASCIIEncoding ascii = new ASCIIEncoding();
            int templen = 0;
            byte[] s = ascii.GetBytes(str);
            for (int i = 0; i < s.Length; i++)
            {
                if ((int)s[i] == 63)
                {
                    templen += 2;
                }
                else
                {
                    templen += 1;
                }
            }
            return templen;
        }

        LedDll.AREARECT GetReact(int left, int top, int width, int height)
        {
            LedDll.AREARECT AreaRect = new LedDll.AREARECT();//区域坐标属性结构体变量
            AreaRect.left = left;
            AreaRect.top = top;
            AreaRect.width = width;
            AreaRect.height = height;
            return AreaRect;

        }
        void InitData()
        {
            info = new WATERBORDERINFO()
            {
                BorderColor = LedDll.COLOR_RED,
                BorderSpeed = 4,
                BorderType = 0,
                BorderValue = 0,
                BorderStyle = 0,
                Flag = 0

            };


            fontProp10 = new LedDll.FONTPROP();//文字属性
            fontProp10.FontName = "宋体";
            fontProp10.FontSize = 10;
            fontProp10.FontColor = LedDll.COLOR_RED;
            fontProp10.FontBold = 0;

            fontProp12 = new LedDll.FONTPROP();//文字属性
            fontProp12.FontName = "宋体";
            fontProp12.FontSize = 12;
            fontProp12.FontColor = LedDll.COLOR_RED;
            fontProp12.FontBold = 0;

            fontProp14 = new LedDll.FONTPROP();//文字属性
            fontProp14.FontName = "宋体";
            fontProp14.FontSize = 14;
            fontProp14.FontColor = LedDll.COLOR_RED;
            fontProp14.FontBold = 0;

            playProp = new LedDll.PLAYPROP();
            playProp.InStyle = 23;
            playProp.DelayTime = 65535;
            playProp.Speed = 1;

        }

    }
}
